package com.ruoyi.system.controller;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.page.PageDomain;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.core.web.page.TableSupport;
import com.ruoyi.common.security.annotation.PreAuthorize;
import com.ruoyi.system.config.EsConfig;
import com.ruoyi.system.domain.TbRoomInfo;
import com.ruoyi.system.service.HouseListService;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.swing.text.Highlighter;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;

/**
 * 【请填写功能名称】Controller
 * 
 * @author wish
 * @date 2021-06-22
 */
@RestController
@RequestMapping("/houselist")
public class TbHouseListController extends BaseController
{
    @Autowired
    private HouseListService houseListService;
    @Autowired
    RestHighLevelClient esRestClient;

    /**
     * 查询【请填写功能名称】列表
     */
    @PreAuthorize(hasPermi = "system:houselist:list")
    @PostMapping("/list")
    public List<Map<String ,Object>> list(TbRoomInfo tbRoomInfo) throws IOException {
      //  startPage();
     /*  List<TbRoomInfo> list = houseListService.selectHouseList(tbRoomInfo);
        for (TbRoomInfo roomInfo : list) {
            String s = JSON.toJSONString(roomInfo);
            IndexRequest request = new IndexRequest("roominfo");
            request.id(roomInfo.getId());
            request.source(s, XContentType.JSON);
            IndexResponse index = esRestClient.index(request, EsConfig.COMMIN_OPTIONS);
        }*/


        //拿到分页的数据
        Integer from = tbRoomInfo.getPageNum();
        Integer size = tbRoomInfo.getPageSize();
        //指定要查询的索引
        SearchRequest searchRequest = new SearchRequest("roominfo");
        // 条件构造器
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //全文搜索
        MatchAllQueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
        //分页
        searchSourceBuilder.from(from);
        searchSourceBuilder.size(size);
        searchSourceBuilder.query(queryBuilder);
        //调用客户端查询
        SearchResponse search = esRestClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHit[] hits = search.getHits().getHits();
        TotalHits totalHits = search.getHits().getTotalHits();
        long values = totalHits.value;
        List<Map<String, Object>> list = Lists.newArrayList();
        //遍历命中的数据也就是查询到的数据
        for (SearchHit hit : hits) {
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            sourceAsMap.put("total",(int) values);
            list.add(sourceAsMap);
        }
        return list;
    }


    @PostMapping("search")
    public List<Map<String, Object>> highlighted(String roomname) throws IOException {
        //定义索引库
        SearchRequest searchRequest = new SearchRequest("roominfo");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //定义query查询
        QueryBuilder queryBuilder = QueryBuilders.matchQuery("pname", roomname);
        //定义高亮查询
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        //设置需要高亮的字段
        highlightBuilder.field("pname")
                // 设置前缀、后缀
                .preTags("<font color='aqua'>")
                .postTags("</font>");
        searchSourceBuilder.query(queryBuilder);
        searchSourceBuilder.highlighter(highlightBuilder);
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = esRestClient.search(searchRequest, RequestOptions.DEFAULT);

        List<Map<String, Object>> list = Lists.newArrayList();
        //遍历高亮结果
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField nameHighlight = highlightFields.get("pname");
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();

            if (nameHighlight != null) {
                Text[] fragments = nameHighlight.getFragments();
                String names = "";
                for (Text text : fragments) {
                    names += text;
                }
                sourceAsMap.put("pname", names);
                list.add(sourceAsMap);
            }
        }
        return list;
    }

}
